package cn.itcast.nems.order.web.controller.b;

import cn.itcast.ic.common.bean.Page;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.account.AccountHolder;
import cn.itcast.nems.common.web.vo.BasePageRequest;
import cn.itcast.nems.manager.msas.MsasManager;
import cn.itcast.nems.manager.util.RequestToEntityConverter;
import cn.itcast.nems.order.dao.dataobject.OrderDO;
import cn.itcast.nems.order.dao.dataobject.OrderPaymentFlowDO;
import cn.itcast.nems.order.service.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itcast.msas.sdk.acm.domain.AccountDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单相关的
 */
@Slf4j
@RestController("bOrderController")
@RequestMapping("/b/order")
@RequiredArgsConstructor
public class OrderController {
    private final MsasManager msasManager;
    private final OrderService orderService;
    private final OrderLineService orderLineService;
    private final OrderDiscountService orderDiscountService;
    private final PaymentReceiptService paymentReceiptService;
    private final OrderPaymentFlowService orderPaymentFlowService;


    // 新增接口：报名订单分页查询
    @GetMapping
    public ResponseEntity<Page<OrderDO>> list(HttpServletRequest request, @RequestParam(value = "page_number", required = false) Integer pageNumber, @RequestParam(value = "page_size", required = false) Integer pageSize) {
        OrderDO myEntity = (OrderDO) RequestToEntityConverter.convert(request, OrderDO.class);
        BasePageRequest<OrderDO> params = new BasePageRequest<>();
        params.setPageNumber(pageNumber);
        params.setPageSize(pageSize);
        params.setCondition(myEntity);
        params.convert();
        log.info("[报名订单分页查询] 请求参数: {} ", params);
        OrderDO condition = params.getCondition();
        return ResponseEntity.ok().body(orderService.list(pageNumber, pageSize, condition));
    }

    // 新增接口：取消报名订单
    @PutMapping("/{orderId}")
    public ResponseEntity<?> orderCanceled(@PathVariable("orderId") String orderId) {
        return ResponseEntity.ok(orderService.cancel(orderId));
    }

    // 新增接口：订单详情-查询订单详情
    @GetMapping("/{orderId}")
    public ResponseEntity<?> orderInfo(@PathVariable("orderId") String orderId) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> orderInfo = orderService.orderInfo(orderId);

        Assert.notNull(orderInfo, "订单不存在");
        map.put("orderInfo", orderInfo);
//        // 新增接口：订单详情-查询订单关联退费单
//        List<Map<String, Object>> orderRefundInfo = orderRefundService.listOrderRefund(orderId);
//        map.put("orderRefundInfo", orderRefundInfo.size() == 0 ? null : orderRefundInfo);
        List<Map<String, Object>> productInfo = orderLineService.listOrderLine(orderId);
        if (productInfo != null && productInfo.size() != 0) {
            Map<String, Object> map1 = productInfo.get(0);
            String campusId = (String) map1.get("product_campus_id");
            String subjectId = (String) map1.get("product_subject_id");
            cn.hutool.core.lang.Assert.isFalse(!AccountHolder.hasEmployeeGroups(campusId, subjectId), BizExceptionProducer.unauthorized("暂无权限"));
        }
        map.put("productInfo", productInfo.size() == 0 ? null : productInfo);
        return ResponseEntity.ok(map);
    }

    // 新增接口：订单详情-查询订单关联优惠
    @GetMapping("/discount/{orderLineId}")
    public ResponseEntity<?> orderDiscount(@PathVariable("orderLineId") String orderLineId) {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> OrderDiscounts = orderDiscountService.listOrderDiscount(orderLineId);
        for (int i = 0; i < OrderDiscounts.size(); i++) {
            Map<String, Object> OrderDiscountMap = OrderDiscounts.get(i);
            Object created_by = OrderDiscountMap.get("created_by");
            if (created_by != null) {
                final AccountDto account = this.msasManager.getAccount(created_by.toString());
                if (account != null) {
                    OrderDiscountMap.put("operator_name", account.getName() + "（" + created_by + "）");
                } else {
                    OrderDiscountMap.put("operator_name", created_by);
                }
            }
        }
        map.put("OrderDiscounts", OrderDiscounts.size() == 0 ? null : OrderDiscounts);
        return ResponseEntity.ok(map);
    }

    // TODO 新增接口：订单详情-查询客户QQ/微信

    // 新增接口：订单详情-查询支付明细
    @PostMapping("/payment/flow/page/list")
    public ResponseEntity<?> orderPaymentFlow(@RequestBody BasePageRequest<OrderPaymentFlowDO> queryParam) {
        queryParam.convert();
        log.info("[订单详情-查询支付明细] 请求参数: {} ", queryParam);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<OrderPaymentFlowDO> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>();
        page.setCurrent(queryParam.getPageNumber());
        page.setSize(queryParam.getPageSize());
        OrderPaymentFlowDO condition = queryParam.getCondition();
        IPage<OrderPaymentFlowDO> data = orderPaymentFlowService.findPageList(page, condition);
        Page<OrderPaymentFlowDO> pageData = Page.of(Long.valueOf(data.getCurrent()).intValue(),
                Long.valueOf(data.getSize()).intValue(),
                Long.valueOf(data.getTotal()).intValue(), data.getRecords());
        return ResponseEntity.ok().body(pageData);
    }

    // 新增接口：订单详情-支付明细-查看收据
    @GetMapping("/payment/receipt/{paymentFlowId}")
    public ResponseEntity<?> paymentReceipt(@PathVariable("paymentFlowId") String paymentFlowId) {
        Map<String, Object> paymentReceipt = paymentReceiptService.getPaymentReceipt(paymentFlowId);
        return ResponseEntity.ok().body(paymentReceipt);
    }

    /**
     * 根据客户名获取订单编号
     *
     * @param customerId
     * @return
     */
    @GetMapping("/nos")
    public ResponseEntity<?> listOrderNoByCustomerName(@RequestParam String customerId) {
        return ResponseEntity.ok(orderService.listOrderNoByCustomerName(customerId));
    }
}
